package com.sharp.socket.io.service;

import com.corundumstudio.socketio.BroadcastOperations;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.sharp.socket.io.dao.mongo.po.TopicChatMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Title: LiveShowMessageService
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2021/9/14 14:05
 */
@Service
@Slf4j
public class ShowMessageService {

    @Resource
    private SocketIOServer socketIOServer;
    @Resource
    private LiveSessionService liveSessionService;


    public void show(SocketIOClient client, TopicChatMessage message) {
        log.debug("To: 客户端[{}] - 发送消息 {}", client.getNamespace().getName(), message);
        client.sendEvent(message.getTopic(), message);
    }

    public void show(String operator, TopicChatMessage message) {
        String namespace = liveSessionService.buildSocketIoNamespace(operator);
        BroadcastOperations operations = socketIOServer.getNamespace(namespace).getBroadcastOperations();
        if (operations != null) {
            log.debug("广播client数量:{}", operations.getClients().size());
            if (CollectionUtils.isNotEmpty(operations.getClients())) {
                for (SocketIOClient client : operations.getClients()) {
                    log.info("{}-{}", client.getNamespace().getName(), client.getSessionId().toString());
                    if (client.getSessionId().toString().equals(message.getSessionId())) {
                        continue;
                    } else {
                        log.info("To: 客户端[{}-{}] - 发送消息 {}", operator, client.getSessionId().toString(), message);
                        client.sendEvent(message.getTopic(), message);
                    }
                }
            }
        }
    }

    public void broadcast(TopicChatMessage message) {
        socketIOServer.getBroadcastOperations().sendEvent(message.getTopic(), message);
    }
}
